package cn.edu.sdjzu.xg.bysj.controller;

import cn.edu.sdjzu.xg.bysj.domain.Teacher;
import cn.edu.sdjzu.xg.bysj.exception.BysjException;
import cn.edu.sdjzu.xg.bysj.service.TeacherService;
import cn.edu.sdjzu.xg.bysj.util.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;

@WebServlet("/teacherCreate.ctl")
public class TeacherCreateCtrl extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应字符编码为UTF8，以便正确响应汉字
        response.setContentType("application/json;charset=UTF-8");
        // 创建JSON对象message，以便往前端响应信息
        JSONObject message_jsonObj = new JSONObject();
        // 将request body转为JSON字串
        String req_jsonStr = JSONUtil.getJSON(request);
        // 将request body解析为JSONObject对象
        JSONObject req_jsonObj = JSON.parseObject(req_jsonStr);
        // 如果请求body为空
        if (req_jsonObj == null){
            message_jsonObj.put("message","未收到请求信息！");
            response.getWriter().println(message_jsonObj);
            return;
        }
        try{
            // 将JSON字串直接转为Java对象
            Teacher teacherToAdd = JSON.parseObject(req_jsonStr, Teacher.class);
            String s = TeacherService.getInstance().add(teacherToAdd);
            message_jsonObj.put("message",s);
/*
            cn.edu.sdjzu.xg.bysj.domain.Teacher teacherToAdd = cn.edu.sdjzu.xg.bysj.util.ControllerHelper.getTeacher(req_jsonObj);
            String s = cn.edu.sdjzu.xg.bysj.service.TeacherService.getInstance().add(teacherToAdd);
            message_jsonObj.put("message",s);
 */
            // 响应teacher_json到前端
            response.getWriter().println(message_jsonObj);
        }catch (BysjException e) {
            message_jsonObj.put("message",e.getMessage());
            response.getWriter().println(message_jsonObj);
            // 每个都要有printStackTrace
            e.printStackTrace();
        }catch (SQLException e){
            message_jsonObj.put("message","数据库操作异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }catch (Exception e){
            message_jsonObj.put("message","网络异常");
            response.getWriter().println(message_jsonObj);
            e.printStackTrace();
        }
    }
}
